<template>
	<view class="pageBox">
		<uni-nav-bar height="88rpx" fixed title="兑换记录" color="#000000" :border="false" left-icon="left"
			@clickLeft="$back" statusBar>
		</uni-nav-bar>
		<view class="navbar-fixed">
			<view class="tabsBG">
				<u-tabs lineHeight="4rpx" :list="dictList.indent_status" keyName="label" :itemStyle="tabsStyle"
					:activeStyle="tabsAStyle" lineColor="#6FA9FF" :current="tabIndex" @change="tabsChange"></u-tabs>
			</view>
		</view>
		<!-- 对于mescroll-body: 需设置:sticky="true", 此应避免在mescroll-body标签前面加其他非定位的元素, 否则下拉区域会被挤出, 无法会隐藏.-->
		<!-- 对于mescroll-uni: 则无需设置:sticky="true", 无其他限制和要求 -->
		<mescroll-body :sticky="true" ref="mescrollRef" :top="mescroll_top" @init="mescrollInit" :down="downOption"
			@down="downCallback" @up="upCallback" :up="upOption">
			<view class="orderContentBox">
				<view class="orderRow" v-for="(item,index) in dataList.rows" :key="index">
					<view class="left flex-column flex-justCenter">
						<view class="goodsName u-line-1" v-if="item.integralCommodity">
							{{item.integralCommodity.commodityName}}
						</view>
						<view class=" flex-alignCenter" v-if="item.integralCommodity">
							<view class="timeText" v-if="listObj.indentStatus!=1">截止时间 {{item.expirationDate}}</view>
							<view class="goodsIntegral" v-if="listObj.indentStatus==1">
								<image src="@/static/activity/activityScore.png"
									style="width: 36rpx;height: 36rpx;margin-right: 10rpx;" mode="scaleToFill"></image>

								{{item.integralCommodity.integral}}积分
							</view>
						</view>
					</view>
					<view class="right">
						<view class="btn" v-if="listObj.indentStatus==1" @click="openExchange(item)">核销</view>
						<view class="goodsIntegral flex-alignCenter" v-if="listObj.indentStatus!=1">
							<image src="@/static/activity/activityScore.png"
								style="width: 36rpx;height: 36rpx;margin-right: 10rpx;" mode="scaleToFill"></image>

							{{item.integralCommodity.integral}}积分
						</view>
					</view>
				</view>
			</view>
		</mescroll-body>
		<u-modal :show="modalShow" :title="modalOptions.title" :confirmText="modalOptions.onfirmText"
			:cancelText="modalOptions.cancelText" :cancelColor="modalOptions.cancelColor" showCancelButton
			:confirmColor="modalOptions.confirmColor" @confirm="modalconfirm" @cancel="closeDialog"
			@close="closeDialog">
			<view class="Modal-slot-content">
				<view class="modalContent">{{modalOptions.content}}</view>
				<u-form labelPosition="left" :model="userInfo" ref="uForm" labelWidth="150rpx">
					<u-form-item label="兑换码" prop="redeemCode">
						<u--input v-model="userInfo.redeemCode"></u--input>
					</u-form-item>
					<u-form-item label="核销人" prop="redeemedBy">
						<u--input v-model="userInfo.redeemedBy"></u--input>
					</u-form-item>
					<u-form-item label="联系方式" prop="contactInfo">
						<u--input v-model="userInfo.contactInfo"></u--input>
					</u-form-item>
				</u-form>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js'
	import * as systemApi from "@/api/system.js"
	import * as vouchersApi from "@/api/vouchers.js"
	import * as exchangeApi from "@/api/exchange.js"
	export default {
		mixins: [MescrollMixin], // 注意此处还需使用MescrollMoreItemMixin (必须写在MescrollMixin后面)
		// components: {
		// 	searchRow
		// },
		data() {
			return {
				//模态框
				modalShow: false,
				//模态框确认方法
				callback: () => {},
				//当前模态框名字
				now_modalShow: '',
				modalOptions: {
					content: '',
					title: '注意',
					onfirmText: '确认',
					confirmColor: '#6FA9FF',
					cancelText: '取消'
				},
				rules: {
					// redeemedBy: {
					// 	type: 'string',
					// 	min: 2,
					// 	required: true,
					// 	message: '请填写核销人',
					// 	trigger: ['blur', 'change']
					// },
					// redeemCode: {
					// 	type: 'string',
					// 	min: 2,
					// 	required: true,
					// 	message: '请填写兑换码',
					// 	trigger: ['blur', 'change']
					// },
					// contactInfo: {
					// 	type: 'string',
					// 	min: 2,
					// 	required: true,
					// 	message: '请填写联系方式',
					// 	trigger: ['blur', 'change']
					// }
				},
				userInfo: {
					userId: '',
					redeemedBy: '',
					redeemCode: '',
					contactInfo: ''
				},
				mescroll_top: '88rpx',
				searchUrl: 'pages/search/afterSales_Search',
				tabsStyle: {
					height: '88rpx',
					boxSizing: 'border-box'
				},
				tabsAStyle: {
					color: '#6FA9FF'
				},
				tabs: [{
						name: '审核中',
						id: 0
					},
					{
						name: '已通过 ',
						id: 1
					},
					{
						name: '不通过',
						id: 2
					},
					{
						name: '售后记录',
						id: -1
					}
				],
				tabIndex: 0,
				tabIndexOld: 0,
				options: {},
				downOption: {
					auto: false // 不自动加载 (mixin已处理第一个tab触发downCallback)
				},
				upOption: {
					auto: false, // 不自动加载
					page: {
						num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
						size: 8 // 每页数据的数量
					},
					noMoreSize: 4, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
					textNoMore: '--这里是底线--',
					empty: {
						tip: '暂无' // 提示
					}
				},
				dataList: {
					records: [],
					rows: [],
					pages: 0,
					size: 0,
					total: 0,
					current: 0
				}, //列表数据
				listObj: {
					indentStatus: 1,
				},
				canReset: false,
				dicts: {
					indent_status: {}
				},
				dictList: {
					indent_status: []
				},
				dataInfo: {}
			}
		},
		mounted() {
			const that = this
			// // #ifdef MP
			// uni.getSystemInfo({
			// 	success: function(res) {
			// 		that.mescroll_top = 88 + 88 + res.statusBarHeight * 2 + 'rpx'
			// 	}
			// })
			// // #endif
		},
		onLoad(options) {
			this.options = options
			this.getDictDataList('indent_status')
		},
		onShow() {
			this.getUserInfo()
			// that.canReset && that.getData()
			// that.canReset = true
		},
		methods: {
			getUserInfo() {
				const that = this
				this.$store.dispatch('userBaseInfo').then(res => {
					console.log(res.user);
					this.userInfo = res.user
					this.eliteInfo = res.eliteInfo
					this.downCallback()
				})
			},
			openExchange(item) {
				const that = this
				this.dataInfo = item
				this.userInfo.redeemedBy = ''
				that.modalOptions.content = `温馨提示：请勿自行核销，由现场工作人员点击，确认核销？`
				// that.callBack = () => {
				// 	that.vouchersexchange()
				// }
				that.openDialog()
			},
			//打开弹窗
			openDialog(openShow = 'modal') {
				this.now_modalShow = openShow
				this[openShow + 'Show'] = true
			},
			//关闭弹窗
			closeDialog() {
				this[this.now_modalShow + 'Show'] = false
				this.callback = () => {}
				this.userInfo.redeemedBy = ''
				//this.modalOptions = { ...modalOptions }
			},
			//弹窗确认触发
			modalconfirm() {
				this.$refs.uForm.validate().then(res => {
					this.writeOff()
				}).catch(errors => {})
				// this.clearSearch()
			},
			writeOff() {
				const that = this
				uni.$u.throttle(() => {
					const params = {
						commodityId: that.dataInfo.commodityId,
						userId: this.dataInfo.userId,
						redeemedBy: that.userInfo.redeemedBy,
						redeemCode: that.userInfo.redeemCode,
						contactInfo: that.userInfo.contactInfo,
					}
					exchangeApi.businessWriteOff(params)
						.then(res => {
							that.$toast1('核销成功', setTimeout(() => {
								that.closeDialog()
								that.downCallback()
							}, 600))
						}).catch(that.closeDialog())
				}, 600)
			},
			getDictDataList(dictType) {
				return new Promise((resolve, reject) => {
					systemApi.dictDataList(dictType).then(({
						rows
					}) => {
						let objs = {}
						let keyValues = []
						rows.forEach((item) => {
							objs[item.dictValue] = item.dictLabel
							keyValues.push({
								label: item.dictLabel,
								text: item.dictLabel,
								value: item.dictValue
							})
						})
						this.dicts[dictType] = objs
						this.dictList[dictType] = keyValues
						resolve({
							objs,
							keyValues,
							rows
						})
					}).catch(reject)
				})
			},
			goto(url, data) {
				this.$navTo(`pages/${url}`, data)
			},
			//手动刷新
			getData() {
				let curMescroll = this.$refs.mescrollItem[0].mescroll
				curMescroll && curMescroll.resetUpScroll()
				curMescroll && curMescroll.scrollTo(0, 0)
			},
			tabsChange(e) {
				this.tabIndexOld = this.tabIndex
				this.tabIndex = e.index
				this.listObj.indentStatus = e.value
				this.dataList.rows = []
				this.downCallback()
			},
			/*下拉刷新的回调 */
			downCallback(page) {
				// 这里加载你想下拉刷新的数据, 比如刷新轮播数据
				// loadSwiper();
				// 下拉刷新的回调,默认重置上拉加载列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
				this.mescroll.resetUpScroll()
			},
			/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
			upCallback(page) {
				//联网加载数据
				const that = this
				if (that.$store.getters.token) {
					this.getDataList({
						pageNum: page.num,
						pageSize: page.size,
						userId: this.userInfo.userId,
						...that.listObj
					}).then(list => {
						const curPageLen = list.rows.length
						const totalSize = list.total
						that.mescroll.endBySize(curPageLen, totalSize)
					}).catch(err => {
						that.mescroll.endErr()
					})
				} else {
					that.mescroll.endBySize(0, 0)
					return
				}
			},
			/**
			 * @param {Object} page 页码
			 */
			getDataList(pageObj) {
				console.log(pageObj);
				const that = this
				return new Promise((resolve, reject) => {
					vouchersApi.vouchersList(pageObj).then((data) => {
						let dataList = JSON.parse(JSON.stringify(that.dataList))
						dataList.pageSize = pageObj.pageSize
						dataList.pageNum = pageObj.pageNum
						dataList.total = data.total
						dataList.pages = Math.ceil(data.total / dataList.pageSize)
						// 合并新数据
						const newList = data.rows
						// 如果是第一页需手动制空列表
						if (pageObj.pageNum == 1) dataList.rows = []
						// 合并新数据
						dataList.rows = dataList.rows.concat(newList)
						that.dataList = dataList
						resolve(that.dataList)
					}).catch(reject)
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.modalContent {
		text-align: center;
		margin: 20rpx 0;
		max-height: 80vh;
	}

	.pageBox {
		.tabsBG {
			padding-left: 30rpx;
			background-color: #F4F7FF;
		}

		background-color: #F4F7FF;

		.orderContentBox {
			padding: 30rpx;
		}

		.orderRow {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx;
			background-color: #fff;
			margin-bottom: 30rpx;
			border-radius: 16rpx;

			.left {
				.goodsName {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #000000;
					margin-bottom: 20rpx;
				}

				.goodsIntegral {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #FF7D00
				}
			}
.timeText {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #979797
				}
			.right {
				flex-shrink: 0;
				text-align: right;

				.btn {
					display: inline-block;
					padding: 16rpx 24rpx;
					background: #008AFF;
					border-radius: 32rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					font-size: 28rpx;
					color: #FFFFFF;
				}

				
			}
		}
	}
</style>